from typing import Dict, Any, Optional
from django.db.models import QuerySet
from submission.models.submission_model import SubmissionModel
from problems.models.problem_model import ProblemModel
from submission.task.tasks import judge_submission


class SubmissionService:
    @staticmethod
    def create_submission(user_id: int, problem_id: int, language: int, code: str) -> SubmissionModel:
        """
        创建代码提交记录
        """
        # 检查题目是否存在
        problem = ProblemModel.objects.filter(id=problem_id, is_delete=False).first()
        if not problem:
            raise ValueError("题目不存在")

        # 检查语言是否支持
        if language not in [0, 1, 3]:  # C, C++, Python
            raise ValueError("不支持的语言类型")

        # 创建提交记录
        submission = SubmissionModel.objects.create(
            user_id=user_id,
            problem_id=problem_id,
            language=language,
            code=code,
            code_size=len(code),
            result=1,  # 等待评测
            times=1,  # 初始提交次数
        )

        # 启动评测任务
        judge_submission(submission.id)

        return submission

    @staticmethod
    def get_submission_detail(submission_id: int) -> Optional[SubmissionModel]:
        """
        获取提交记录详情
        """
        return SubmissionModel.objects.filter(
            id=submission_id,
            is_delete=False
        ).first()

    @staticmethod
    def get_submission_list(
        problem_id: Optional[int] = None,
        user_id: Optional[int] = None,
        page: int = 1,
        page_size: int = 10
    ) -> QuerySet:
        """
        获取提交记录列表
        """
        queryset = SubmissionModel.objects.filter(is_delete=False)

        if problem_id:
            queryset = queryset.filter(problem_id=problem_id)
        if user_id:
            queryset = queryset.filter(user_id=user_id)

        return queryset.order_by('-create_time')

    @staticmethod
    def get_user_problem_submissions(user_id: int, problem_id: int) -> QuerySet:
        """
        获取用户某题目的所有提交记录
        """
        return SubmissionModel.objects.filter(
            user_id=user_id,
            problem_id=problem_id,
            is_delete=False
        ).order_by('-create_time')
